package com.github.cyf.task;

import com.github.cyf.common.util.MDCUtil;

import java.util.Map;
import java.util.concurrent.Callable;

/**
 * 方式二：包装任务
 * @author chenyifan
 * @create 2024-09-03 14:34
 */
public class MdcCallable<T> implements Callable<T> {

    private Map<String, String> contextMap;
    private Callable<T> callable;

    public MdcCallable(Callable<T> callable) {
        this.contextMap = MDCUtil.getCopyOfContextMap();
        this.callable = callable;
    }

    @Override
    public T call() throws Exception {
        try {
            MDCUtil.setContextMap(contextMap);
            return callable.call();
        } finally {
            MDCUtil.clear();
        }
    }
}
